package controll;

import entity.Customer;
import org.springframework.http.ResponseEntity;
import Service.CustomerService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Resource
    private CustomerService customerService;

    // 添加客户
    @PostMapping("/add")
    public ResponseEntity<?> addCustomer(@RequestBody Customer customer) {
        try {
            customerService.addCustomer(customer);
            return ResponseEntity.ok().body("客户添加成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 修改客户信息
    @PutMapping("/update")
    public ResponseEntity<?> updateCustomer(@RequestBody Customer customer) {
        try {
            customerService.updateCustomer(customer);
            return ResponseEntity.ok().body("客户信息修改成功");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("修改失败：" + e.getMessage());
        }
    }

    // 删除客户
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteCustomer(@PathVariable String id) {
        try {
            customerService.deleteCustomer(id);
            return ResponseEntity.ok().body("客户删除成功");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("删除失败：" + e.getMessage());
        }
    }

    // 查询客户详情
    @GetMapping("/{id}")
    public ResponseEntity<?> getCustomer(@PathVariable String id) {
        Customer customer = customerService.getCustomer(id);
        return customer != null ?
                ResponseEntity.ok().body(customer) :
                ResponseEntity.notFound().build();
    }

    // 导出客户数据到 Excel
    @GetMapping("/export")
    public void exportCustomer(HttpServletResponse response) {
        try {
            customerService.exportCustomer(response);
        } catch (IOException e) {
            try {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"message\":\"导出失败：" + e.getMessage() + "\"}");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    @PostMapping("/import")
    // 从Excel 导入客户数据
    public ResponseEntity<?> importCustomer(@RequestParam("file") MultipartFile file) {
        try {
            customerService.importCustomer(file);
            return ResponseEntity.ok().body("客户数据导入成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("导入失败：" + e.getMessage());
        }
    }
}